package net.dgg.dggcloud.service.jrcrm.common.webscoket.redis.dao.impl;

import net.dgg.dggcloud.service.jrcrm.common.webscoket.redis.dao.WSRedisDAO;
import net.dgg.dggcloud.service.jrcrm.constant.CommonConstant;
import  net.dgg.dggcloud.service.jrcrm.utils.ResourceUtils;
import  net.dgg.dggcloud.service.jrcrm.utils.SerializeUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.WebSocketSession;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Service("wsRedisDAO")
public class WSRedisDAOImpl implements WSRedisDAO {

    private JedisCluster jedisCluster;

    /**
     * 构造函数，初始化redis参数
     */
    public WSRedisDAOImpl() {
        String servers = ResourceUtils.getResource("dggcloud").getValue("redis.servers");
        String[] hostandports = servers.split(";");
        Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();
        for (String recore : hostandports) {
            String server = recore.split(":")[0];
            String port = recore.split(":")[1];
            HostAndPort hostAndPort = new HostAndPort(server, Integer.valueOf(port));
            jedisClusterNodes.add(hostAndPort);
        }
        this.jedisCluster = new JedisCluster(jedisClusterNodes);
    }

    @Override
    public void sendMessage(String channel, Serializable message) {
        jedisCluster.publish(channel.getBytes(), SerializeUtils.serialize(message));
    }

    @Override
    public void sendHashMapByOnlineUser(WebSocketSession session) {
        Map<String, Object> params = session.getAttributes();
        String loginName = session.hashCode() + ":";
        long userId = 0;
        String userName = "";
        if (params != null) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (entry.getKey().equals(CommonConstant.WEBSOCKET_USER_LOGINNAME)) {
                    loginName += (String) entry.getValue();
                }
                if (entry.getKey().equals(CommonConstant.WEBSOCKET_USER_SESSION)) {
                    userId = (long) entry.getValue();
                }
                if (entry.getKey().equals(CommonConstant.WEBSOCKET_USER_NAME)) {
                    userName = (String) entry.getValue();
                }
            }
            jedisCluster.hset(CommonConstant.ONLINE_USER, loginName, String.valueOf(userId));
            if (jedisCluster.ttl(CommonConstant.ONLINE_USER) == -1) {
                jedisCluster.expire(CommonConstant.ONLINE_USER, 4 * 3600);
            }
        }
    }

    @Override
    public void delHashMapByOnlineUser(String... key) {
        jedisCluster.hdel(CommonConstant.ONLINE_USER, key);
    }
}